package com.JingYan.config;

import org.springframework.core.task.TaskDecorator;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @program: iron-tcm-api
 * @ClassName: ContextDecorator.java
 * @author: DongJiaQi
 * @version: 1.0.0
 * @Description: 线程池装饰器 主要将主线程的数据 传递给异步线程
 * @createTime 2023年08月02日 08:32:00
 */
public class ContextDecorator  implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        RequestAttributes context = RequestContextHolder.currentRequestAttributes();
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return () -> {
            try {
                RequestContextHolder.setRequestAttributes(context);
                SecurityContextHolder.setContext(securityContext);
                runnable.run();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        };
    }
}
